package by.grsu.epam.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class GenericDAOImpl<T, PK extends Serializable> implements GenericDAO<T, PK>{
	
	@Autowired
	SessionFactory sessionFactory;
	
	private Class<T> entityClass;
	
	public GenericDAOImpl(){
	}
	
	public GenericDAOImpl(Class<T> clazz){
		this.entityClass = clazz;
	}

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public PK save(T o) {
		return (PK) getSession().save(o);
	}

	@Override
	public void update(T o) {
		getSession().update(o);		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll() {
		Criteria cr = getSession().createCriteria(entityClass);
		return (List<T>) cr.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findByCriteria(Criterion... criterion) {
		Criteria crit = getSession().createCriteria(entityClass);
		for (Criterion c : criterion) {
			crit.add(c);
		}
		return (List<T>) crit.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public T findById(PK id) {
		return (T) getSession().get(entityClass, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void delete(PK id) {
		T persistentObject = (T) getSession().load(entityClass, id);
		try {
			getSession().delete(persistentObject);
		} catch (NonUniqueObjectException e) {
			T instance = (T) getSession().merge(persistentObject);
			getSession().delete(instance);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void delete(T persistentObject) {
		try {
			getSession().delete(persistentObject);
		} catch (NonUniqueObjectException e) {
			T instance = (T) getSession().merge(persistentObject);
			getSession().delete(instance);
		}
	}
}
